import { defineComponent } from 'vue';
import { PagedListingComponentBase } from '/@/shared/component-base';
import { UserServiceProxy, GetUsersInput } from '/@/shared/service-proxies';
import { AppConsts } from '/@/abpPro/AppConsts';
import { impersonationService } from '/@/shared/auth';
import {
  EntityDtoOfInt64,
  UserExtensionServiceProxy,
  UserListDto,
} from '/@/shared/service-proxies/service-proxies';
import {
  CheckCircleTwoTone,
  CloseCircleTwoTone,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  LoginOutlined,
  UnlockOutlined,
  CodepenOutlined,
  FilterOutlined,
  DownOutlined,
} from '@ant-design/icons-vue';
import { IPagedRequestDto } from '/@/shared/component-base/interfaces';
import { RoleCombox, PermissionCombox } from '/@/app/admin-shared';
import GExcelImport from '/@/shared/components/g-excel-import/index.vue';
import CreateOrEditUserCompent from './create-or-edit-user/create-or-edit-user.vue';
import EditUserPermissionsCompent from './edit-user-permission/edit-user-permission.vue';
import { ColumnType } from 'ant-design-vue/lib/table';
import { fileDownloadService } from '/@/shared';

export default defineComponent({
  name: 'Users',
  components: {
    PermissionCombox,
    RoleCombox,
    CheckCircleTwoTone,
    CloseCircleTwoTone,
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    LoginOutlined,
    UnlockOutlined,
    CodepenOutlined,
    FilterOutlined,
    DownOutlined,
    GExcelImport,
  },
  mixins: [PagedListingComponentBase],
  data() {
    return {
      /** 用户api */
      userSer: new UserServiceProxy(),
      /** 是否显示高级过滤 */
      advancedFiltersVisible: false,
      /** 选中的权限过滤 */
      selectedPermission: [] as any,
      /** 数据 */
      dataList: [] as UserListDto[],
      /** 选中的角色Ids过滤 */
      role: [] as number[],
      /** 是否已验证邮箱过滤 */
      isEmailConfirmed: undefined,
      /** 是否激活过滤 */
      isActive: undefined,
      _userExtensionService: new UserExtensionServiceProxy(),
      fileDownloadSer: fileDownloadService,
    };
  },
  methods: {
    /**
     * 获取数据
     */
    fetchDataList(request: IPagedRequestDto, finishedCallback?: () => void) {
      const input = new GetUsersInput();
      input.permission = this.selectedPermission;
      input.role = this.role;
      input.isEmailConfirmed = this.isEmailConfirmed;
      input.isActive = this.isActive;
      input.filterText = this.filterText;
      input.sorting = request.sorting;
      input.maxResultCount = request.maxResultCount;
      input.skipCount = request.skipCount;
      this.userSer
        .getPaged(input)
        .finally(() => {
          finishedCallback!();
        })
        .then((res) => {
          this.showPaging(res);
        });
    },
    /**
     * table默认配置 （是否禁用）
     */
    getCheckboxProps(item: UserListDto) {
      return {
        disabled: this.isAdmin(item) || this.isCurrentUser(item),
      };
    },
    /**
     * 添加用户  修改用户
     */
    createOrEdit(item?: UserListDto) {
      //alert('模态框')
      this.modalHelper
        .create(
          CreateOrEditUserCompent,
          {
            id: item != null ? item.id : null,
            username: item != null ? item.userName : null,
          },
          {
            width: '400px',
          },
        )
        .subscribe((res) => {
          if (res) {
            this.refresh();
          }
        });
    },
    /**
     * 批量删除
     */
    batchDelete() {
      if (this.selectedCount <= 0) {
        this.message.warn(this.l('PleaseSelectAtLeastOneItem'));
        return;
      }
      this.message.confirm(
        this.l('ConfirmDeleteXItemsWarningMessage', this.selectedCount),
        '',
        (res: any) => {
          if (res) {
            const ids = [...this.selectedRowKeys];
            this.isTableLoading = true;
            this.userSer
              .batchDelete(ids)
              .finally(() => {
                this.isTableLoading = false;
              })
              .then(() => {
                this.refreshGoFirstPage();
                this.notify.success(this.l('SuccessfullyDeleted'));
              });
          }
        },
      );
    },
    /**
     * 单个删除
     */
    deleteItem(item: UserListDto) {
      if ((item as any).isStatic) {
        this.message.warn(
          this.l('XUserCannotBeDeleted', AppConsts.userManagement.defaultAdminUserName),
        );
        return;
      }
      this.isTableLoading = true;
      this.userSer
        .delete(item.id)
        .finally(() => {
          this.isTableLoading = false;
        })
        .then(() => {
          this.refreshGoFirstPage();
          this.notify.success(this.l('SuccessfullyDeleted'));
        });
    },
    /*下载模板*/
    downloadTemplate() {
      this._userExtensionService.userExtensionDownloadTemplate().then((result) => {
        this.fileDownloadSer.downloadTempFile(result);
      });
    },

    uploadPictureChange(info: string) {
      this._userExtensionService.importUserExcel(info).then((item) => {
        (this.$refs as any).excelImportModel.initImportReturn(item);
        this.refresh();
      });
    },
    /** 筛选权限发生变更 */
    selectedPermissionChange(permissions: string[]) {
      this.selectedPermission = permissions;
      this.getSearchData();
    },
    /** 角色过滤选择 */
    selectedRoleChange(roles: number[]) {
      this.role = roles;
      this.getSearchData();
    },
    /** 是否是当前用户 */
    isCurrentUser(item: UserListDto) {
      return item.id === this.abpSession.userId;
    },
    /** 是否是管理员 */
    isAdmin(item: UserListDto) {
      return (
        item.userName === AppConsts.userManagement.defaultAdminUserName ||
        item.userName === AppConsts.superUserManagement.defaultAdminUserName
      );
    },
    /** 是否为系统默认不可删除的SuperAdmin用户 */
    isSuperAdmin(item: UserListDto): boolean {
      return item.userName === AppConsts.superUserManagement.defaultAdminUserName;
    },
    /** 是否显示解锁按钮 */
    enabledUnlock() {
      return (
        this.isGranted('Pages.Administration.Users.Edit') &&
        this.setting.getBoolean('Abp.Zero.UserManagement.UserLockOut.IsEnabled')
      );
    },
    /** 使用此账户登录 */
    tenantImpersonateLogin(item: UserListDto) {
      impersonationService.impersonate(item.id, this.abpSession.tenantId);
    },
    /** 编辑用户权限 */
    editUserPermissions(item: UserListDto) {
      this.modalHelper
        .create(
          EditUserPermissionsCompent,
          { id: item.id, userName: item.userName },
          {
            width: '420px',
          },
        )
        .subscribe((res) => {
          if (res) {
            this.refresh();
          }
        });
    },
    /** 解锁 */
    unlockTenantAdminUser(item: UserListDto) {
      this.isTableLoading = true;
      const input: EntityDtoOfInt64 = new EntityDtoOfInt64();
      input.init(item);
      this.userSer
        .unlock(input)
        .finally(() => {
          this.isTableLoading = false;
        })
        .then(() => {
          this.refresh();
          this.notify.success(this.l('UserUnblocked'));
        });
    },
    getColumns(): ColumnType<UserListDto>[] {
      return [
        {
          title: 'No',
          customRender: ({ index }) => {
            const a = (this.pageNumber - 1) * this.pageSize + (index + 1);
            return a;
          },
          width: 60,
          fixed: 'left',
        },
        {
          title: this.l('UserName'),
          dataIndex: 'userName',
          key: 'username',
          width: 200,
          ellipsis: true,
          sorter: {
            multiple: 0,
          },
        },
        {
          title: this.l('Roles'),
          dataIndex: 'roles',
          key: 'roles',
          width: 200,
          ellipsis: true,
        },
        {
          title: this.l('EmailAddress'),
          dataIndex: 'emailAddress',
          key: 'emailAddress',
          width: 200,
          ellipsis: true,
          sorter: {
            multiple: 0,
          },
        },
        // 邮箱验证
        {
          title: this.l('EmailConfirm'),
          dataIndex: 'isEmailConfirmed',
          key: 'isEmailConfirmed',
          filters: this.booleanFilterList,
          filterMultiple: false,
          width: 135,
          ellipsis: true,
        },
        // 是否激活
        {
          title: this.l('Active'),
          dataIndex: 'isActive',
          key: 'isActive',
          filters: this.booleanFilterList,
          filterMultiple: false,
          width: 100,
          ellipsis: true,
          sorter: {
            multiple: 0,
          },
        },
        {
          title: this.l('LastLoginTime'),
          dataIndex: 'lastLoginTime',
          width: 200,
          ellipsis: true,
          sorter: {
            multiple: 0,
          },
        },
        {
          title: this.l('CreationTime'),
          dataIndex: 'creationTime',
          key: 'creationTime',
          width: 200,
          ellipsis: true,
          sorter: {
            multiple: 0,
          },
        },
        {
          title: this.l('Actions'),
          dataIndex: 'actions',
          key: 'actions',
          width: 250,
          ellipsis: true,
          fixed: 'right',
        },
      ];
    },
  },
});
